package net.lengwang.iot.middleware.network;

import net.lengwang.iot.middleware.packet.Packet;
import net.lengwang.iot.middleware.packet.request.PacketParser;

public class HandshakePacket extends Packet {
    public HandshakePacket() {
        this.startFlag = new byte[]{(byte) 0xBE, (byte) 0xBE};
        this.length = 0x04;
        this.command = (byte) 0x90;
        this.version = 0x01;
        this.crc = new byte[]{0x00, 0x00};
        this.endFlag = new byte[]{(byte) 0xEB, (byte) 0xEB};
    }

    private int sequenceNumber;

    @Override
    public byte[] toBytes() {
        byte[] packet = new byte[11];
        packet[0] = startFlag[0];
        packet[1] = startFlag[1];
        packet[2] = length;
        packet[3] = command;
        packet[4] = version;
        packet[5] = (byte) (sequenceNumber >> 8);
        packet[6] = (byte) (sequenceNumber & 0xFF);
        packet[7] = crc[0];
        packet[8] = crc[1];
        packet[9] = endFlag[0];
        packet[10] = endFlag[1];
        return packet;
    }

    @Override
    public void fromBytes(byte[] data) {
        if (data.length != 11) {
            throw new IllegalArgumentException("Invalid packet length");
        }
        startFlag = new byte[]{data[0], data[1]};
        length = data[2];
        command = data[3];
        version = data[4];
        sequenceNumber = (short) ((data[5] << 8) | (data[6] & 0xFF));
        crc = new byte[]{data[7], data[8]};
        endFlag = new byte[]{data[9], data[10]};
    }

    public int getSequenceNumber() {
        return sequenceNumber;
    }

    public void setSequenceNumber(int sequenceNumber) {
        this.sequenceNumber = sequenceNumber;
    }
}
